<template>
  <div class="search-suggestion">
    <van-cell v-for="(item,index) in list" :key="index"  icon="search" @click="$emit('search',item)">
      <div slot="title" v-html="heightActive(item)"></div>
    </van-cell>
  </div>
</template>

<script>
  import { getSearchSuggestion } from '@/api/search'
  // lodash 支持按需加载，有利于打包结果优化
  import { debounce } from "lodash"
  export default {
    name:'SearchSuggestion',
    data() {
      return {
        list: [] // 搜索建议内容
      }
    },
    props:{
      // 接收输入框数据
      searchValue:{
        type:String,
        required:true
      }
    },
    watch:{
      searchValue:{
        deep:false,
        immediate:true, // 一开始就触发一次
        // debounce(function(){ ... },防抖时间) ==> 返回防抖函数
        handler:debounce(function(){
          this.loadSearchSuggestion()
        },200)
      }
    },
    methods: {
      // 获取搜索建议
      async loadSearchSuggestion() {
        try {
          let {data:res} = await getSearchSuggestion(this.searchValue)
          this.list = res.data.options
        } catch (error) {
          console.dir(error)
          this.$toast.fail('获取搜索建议失败')
        }
      },
      // 关键字高亮
      heightActive(val){
        let reg = new RegExp(this.searchValue,'gi')
        return val.replace(reg,`<span style="color:red;">${this.searchValue}</span>`)
      }
    },
  }
</script>

<style lang="less" scoped>

</style>